package com.fastCms.business.bim.manage.impl;

import com.alibaba.fastjson.JSON;
import com.fastCms.business.bim.daos.DataRepairMapper;
import com.fastCms.business.bim.daos.DeviceMapper;
import com.fastCms.business.bim.manage.DataRepairManageService;
import com.fastCms.business.bim.pojo.entity.DataRepair;
import com.fastCms.business.bim.pojo.entity.Device;
import com.fastCms.business.bim.pojo.po.ClearCarBillPO;
import com.fastCms.business.bim.pojo.po.ClearCarBillRecordPO;
import com.fastCms.business.bim.pojo.vo.ClearCarBillDetailRecordVO;
import com.fastCms.business.bim.pojo.vo.ClearCarBillDetailVO;
import com.fastCms.business.bim.pojo.vo.ClearCarBillVO;
import com.fastCms.business.bim.service.DataRepairService;
import com.fastCms.business.bim.service.DeviceService;
import com.fastCms.business.frame.pojo.PageParam;
import com.fastCms.business.frame.response.ApiResponse;
import com.fastCms.business.frame.response.ResponseUtil;
import com.fastCms.business.frame.utils.CommonsUtil;
import com.fastCms.business.frame.utils.PositionUtils;
import com.fastCms.business.frame.utils.gps.GpsUtil;
import com.fastCms.business.frame.utils.gps.TrackVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@Component
@Slf4j
public class DataRepairManageServiceImpl implements DataRepairManageService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DataRepairMapper dataRepairMapper;


    @Autowired
    private DeviceService deviceServiceImpl;

    @Autowired
    private DataRepairService dataRepairServiceImpl;

    @Override
    public PageInfo<ClearCarBillVO> clearCarBill(PageParam<ClearCarBillPO> pageParam) {
        int deviceTypeId = 23;
        PageInfo<ClearCarBillVO> result = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize())
            .doSelectPageInfo(() ->
                deviceMapper.getClearCarDevice(deviceTypeId)
            );

        List<ClearCarBillVO> billList = result.getList();
        if (CollectionUtils.isNotEmpty(billList)) {
            billList.forEach(bill -> {
                double todayTotalMile = dataRepairMapper.countTodayMile(bill.getDeviceId());
                int todayTotalChange = dataRepairMapper.countTodayChange(bill.getDeviceId());
                bill.setMile(todayTotalMile / 1000);
                bill.setTodayChange(todayTotalChange);
            });
        }
        return result;
    }

    @Override
    public ApiResponse<ClearCarBillDetailVO> clearCarBillDetail(Integer deviceId) {
        Device device = deviceServiceImpl.findById(deviceId);
        ClearCarBillDetailVO detailVO = new ClearCarBillDetailVO();
        detailVO.setStatus(1);
        detailVO.setIsGps("GPS定位");
        detailVO.setDeviceCode(device.getDeviceCode());
        detailVO.setCreateTime(new Date());
        return ResponseUtil.success(detailVO);
    }

    @Override
    public ApiResponse<PageInfo<ClearCarBillDetailRecordVO>> clearCarBillDetailRecord(PageParam<ClearCarBillRecordPO> pageParam) {

        ClearCarBillRecordPO recordPO = pageParam.getQueryFields();
        PageInfo<ClearCarBillDetailRecordVO> result = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize())
            .doSelectPageInfo(() ->
                dataRepairMapper.getClearRecord(recordPO)
            );
        return ResponseUtil.success(result);
    }

    @Override
    public void saveCarTrack() {
        //获取到当前最新的
        TrackVO track = GpsUtil.getTrack("13808350053");

        String lat = track.getLat();
        String lng = track.getLng();

        int deviceId = 579;
        DataRepair dataRepair = dataRepairMapper.getNewestDataByDeviceId(deviceId); //当天最新的那条
        if (null == dataRepair) {
            dataRepair = new DataRepair();
            CommonsUtil.initEntity(dataRepair);
            dataRepair.setStatus(0);
            dataRepair.setJsonData(JSON.toJSONString(track));
            dataRepair.setDeviceId(deviceId);
            dataRepair.setMile(0L);
            dataRepair.setTimelong(0L);
            dataRepair.setLat(lat);
            dataRepair.setLng(lng);
            dataRepairServiceImpl.save(dataRepair);
            return;
        }

        int oldStatus = dataRepair.getStatus();
        String newStatus = "0";
        if (newStatus != null) {
            newStatus = track.getStatus();
        }

        //作业时长 形式里程
        //


        //静止变运行
        if (oldStatus != 1 && newStatus.equals("1")) {

            run(dataRepair, track);
            dataRepair.setStatus(1);
            dataRepairServiceImpl.updateById(dataRepair);
            //继续运行
        } else if (oldStatus == 1 && newStatus.equals("1")) {

            run(dataRepair, track);
            dataRepair.setStatus(1);
            dataRepairServiceImpl.updateById(dataRepair);
            //运行变静止
        } else if (oldStatus == 1 && !newStatus.equals("1")) {

            run(dataRepair, track);
            dataRepair.setStatus(2);
            dataRepairServiceImpl.updateById(dataRepair);

            newTrack(deviceId, track);
        }

    }

    private void run(DataRepair dataRepair, TrackVO track) {
        double distance = PositionUtils.getDistance(Double.valueOf(track.getLat()), Double.valueOf(track.getLng()), Double.valueOf(dataRepair.getLat()), Double.valueOf(dataRepair.getLng()));
        dataRepair.setLat(track.getLat());
        dataRepair.setLng(track.getLng());

        BigDecimal distanceBig = new BigDecimal(distance * 5);
        dataRepair.setMile(distanceBig.longValue() + dataRepair.getMile());
        long time = new Date().getTime() - dataRepair.getCreateTime().getTime();
        dataRepair.setTimelong(time / 1000 / 60);
    }

    private void newTrack(Integer deviceId, TrackVO track) {
        DataRepair dataRepair = new DataRepair();
        CommonsUtil.initEntity(dataRepair);
        dataRepair.setStatus(0);
        dataRepair.setTimelong(0L);
        dataRepair.setJsonData(JSON.toJSONString(track));
        dataRepair.setDeviceId(deviceId);
        dataRepair.setLat(track.getLat());
        dataRepair.setLng(track.getLng());
        dataRepair.setMile(0L);
        dataRepairServiceImpl.save(dataRepair);
    }

}
